#  Image class v 0.1
#  Copyright (C) 2010 John Donovan - mersey.viking@gmail.com

#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at

#  http://www.apache.org/licenses/LICENSE-2.0

#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import numpy.ma

class Image(numpy.ma.MaskedArray):
    def __new__(cls, input_array, tile_shape=(20, 20)):
        obj = numpy.ma.asarray(input_array).view(cls)
        obj.tile_shape = tile_shape
        obj.tile_xnum = obj.shape[1] / tile_shape[0]
        obj.tile_ynum = obj.shape[0] / tile_shape[1]
        return obj

    def __array_finalize__(self, obj):
        if obj is None: return
        
        self.tile_shape = getattr(obj, "tile_shape", (20, 20))
        self.tile_xnum = getattr(obj, "tile_xnum", 1)
        self.tile_ynum = getattr(obj, "tile_ynum", 1)
        numpy.ma.MaskedArray.__array_finalize__(self, obj)

    def tiles(self):
        for ind in range(self.tile_xnum * self.tile_ynum):
            y, x = divmod(ind, self.tile_xnum)
            yield self[y * self.tile_shape[1]:(y + 1) * self.tile_shape[1], \
                       x * self.tile_shape[0]:(x + 1) * self.tile_shape[0]]
